package com.abl.tomcat.http;

import com.abl.tomcat.mapper.Mapper;
import com.abl.tomcat.util.FileKit;
import com.abl.tomcat.util.LogKit;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URI;
import java.util.Arrays;

/**
 * 处理客户端请求
 */
public class HandlerRequest implements Runnable {
    Socket client;

    public HandlerRequest(Socket client) {
        this.client = client;
    }

    /**
     * TODO 1.封装 Request 对象
     * TODO 2.封装 Response 对象
     */
    @Override
    public void run() {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            writer = new PrintWriter(client.getOutputStream());

            //TODO 1.封装 Request 对象
            Request request = new Request();
            request.init(null);
            //TODO 2.封装 Response 对象
            Response response = new Response();
            response.init(null);


            //读取请求信息
            String line = reader.readLine();
            String[] lines = line.split(" ");
            String requestMethod = lines[0];
            String requestURI = lines[1];
            LogKit.info("line : " + line);
            LogKit.info("lines : " + Arrays.asList(lines));
            LogKit.info("requestMethod : " + requestMethod);
            LogKit.info("requestURI : " + requestURI + "\n\n");


            URI uri = new URI(requestURI);
            System.out.println(uri.getScheme());
            System.out.println(uri.getPath());
            System.out.println(uri.getQuery());

            //获取输出流，拼接返回信息
            //返回请求信息
            StringBuilder responseStr = new StringBuilder();
            responseStr.append("HTTP/1.1 200 OK\n");//响应行

            //处理静态资源
            if (requestURI.contains("/static/")) {
                responseStr.append("content-type:text/html;charset=utf-8\n\n");
                BufferedReader fileReader = null;
                try {
                    fileReader = new BufferedReader(new InputStreamReader(FileKit.getResourceAsStream(requestURI)));
                    String temp;
                    while ((temp = fileReader.readLine()) != null) {
                        responseStr.append(temp);
                    }
                }
                //404 处理
                catch (FileNotFoundException e) {
                    fileReader = new BufferedReader(new InputStreamReader(FileKit.getResourceAsStream("/static/404.html")));
                    String temp;
                    while ((temp = fileReader.readLine()) != null) {
                        responseStr.append(temp);
                    }
                }
                //关闭流
                finally {
                    if (fileReader != null) {
                        fileReader.close();
                    }
                }
                writer.print(responseStr);
                writer.flush();
            }

            //处理动态资源
            else {
                //获取请求参数
                //requestURI : /register
                String[] split = requestURI.split("[?]");
                String servlet = split[0];

                //获取Servlet类路径，反射创建对象
                String servletClass = Mapper.getServletClass(servlet);
                if (servletClass != null) {
                    Class<?> aClass = Class.forName(servletClass);
                    Servlet o = (Servlet) aClass.getDeclaredConstructor().newInstance();
                    //执行
                    o.service(request, response);
                    //销毁
                    o.destroy(request, response);
                    //
                    responseStr.append("content-type:application/json;charset=utf-8\n\n");
                    responseStr.append("{\"code\":200,\"message\":\"请求成功，但是详细功能正在开发中.....\",\"data\":null}");
                    writer.print(responseStr);
                    writer.flush();
                }
                //404
                else {
                    responseStr.append("content-type:application/json;charset=utf-8\n\n");
                    responseStr.append("{\"code\":500,\"message\":\"暂未暂未开发\",\"data\":null}");
                    writer.print(responseStr);
                    writer.flush();
                }
            }


        }
        //
        catch (Exception e) {
            e.printStackTrace();
        }
        //
        finally {

            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }
    }
}
